package ar.com.kique.persistence.dao.impl;

import java.util.List;

import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import ar.com.kique.model.CentroCosto;
import ar.com.kique.model.Empleado;
import ar.com.kique.model.Gasto;
import ar.com.kique.persistence.dao.GastoDAO;



public class GastoDAOHibernate implements GastoDAO {

	private static SessionFactory  sessionFactory = configureSessionFactory();
	private static ServiceRegistry serviceRegistry;

	private static SessionFactory configureSessionFactory() throws HibernateException {
	    Configuration configuration = new Configuration();
	    configuration.configure();
	    serviceRegistry = new ServiceRegistryBuilder().applySettings(((Configuration) configuration).getProperties()).buildServiceRegistry();        
	    sessionFactory = ((Configuration) configuration).buildSessionFactory(serviceRegistry);
	    return sessionFactory;
	}
	
	@Override
	public Gasto persistir(Gasto gasto) {
		Session session = sessionFactory.openSession();
	    session.beginTransaction();
	    session.saveOrUpdate(gasto);
	    session.getTransaction().commit();
	    session.close();
	    return gasto;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Gasto> buscarGastos() {
		Session session = sessionFactory.openSession();
	    Query query = session.createQuery("select g from " + " Gasto g");
	    
	    return (List<Gasto>) query.list();
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public List<Gasto> buscarGastos(CentroCosto cCosto) {
		Session session = sessionFactory.openSession();
	    Query query = session.createQuery("select g from " + " Gasto g"
	        + " where g.solicitudGasto.centroCosto = :cCosto");
	    query.setParameter("cCosto", cCosto);
	    return (List<Gasto>) query.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Gasto> buscarGastos(Empleado empleado) {
		Session session = sessionFactory.openSession();
		Query query = session.createQuery("select g from " + " Gasto g"
		        + " where g.solicitudGasto.empleado = :empleado");
		query.setParameter("empleado", empleado);
		return (List<Gasto>) query.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Gasto> buscarGastos(CentroCosto cCosto, Empleado empleado) {
		Session session = sessionFactory.openSession();
		Query query = session.createQuery("select g from " + " Gasto g"
		        + " where g.solicitudGasto.empleado = :empleado AND g.solicitudGasto.centroCosto = :cCosto");
		query.setParameter("empleado", empleado);
		query.setParameter("cCosto", cCosto);
		return (List<Gasto>) query.list();
	}

}
